// Created by Amit Mudgal (Principal Consultant - MicroStrategy Professional Services ) on 6/16/2014 for GMS

package com.AmericanExpress.Security;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import com.AmericanExpress.Logger.Log;
import com.microstrategy.utils.log.Level;

public class QueryExecution {

	private static final String CLASS_NAME = "com.AmericanExpress.Security";
	private static Level FINE = Level.FINE;
	private static Level WARN = Level.WARNING;
	private static Level ERROR = Level.SEVERE;

	public static Connection SQLconnect(String SQLServer, String SQLServerDB,
			String SQLServerUID, String SQLServerPWD, String drivername,
			String JDBC_URL, String port) {
		String METHOD_NAME = "SQLconnect";
		Connection conn = null;

		String connectionURL = JDBC_URL + SQLServer + ":" + port + "/"
				+ SQLServerDB;
		// String connectionURL ="jdbc:jtds:sqlserver://" + SQLServer + ":1433/"
		// + SQLServerDB ;
		// String connectionURL ="jdbc:netezza://" + SQLServer +":5480/" +
		// SQLServerDB;
		try {
			Class.forName(drivername);
			conn = DriverManager.getConnection(connectionURL, SQLServerUID,
					SQLServerPWD);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
			Log.generateLog(ERROR, CLASS_NAME, METHOD_NAME,
					"Error while Connecting to DB (Class not found) : " + e);
		} catch (Exception e) {
			e.printStackTrace();
			Log.generateLog(ERROR, CLASS_NAME, METHOD_NAME,
					"Error while Connecting to DB : " + e);
		}
		return conn;
	}

	public static boolean SQLDisconnect(Connection conn) {
		String METHOD_NAME = "SQLDisconnect";
		try {
			conn.close();
		} catch (SQLException e) {
			Log.generateLog(WARN, CLASS_NAME, METHOD_NAME,
					"Error while disconnecting from DB : " + e);
			return false;
		}
		return true;
	}

	public static ResultSet ExecSQLQuery(Connection conn, String SQL) {
		System.out.println("** SQL::" + SQL);
		String METHOD_NAME = "ExecSQLQuery";
		ResultSet rs = null;
		// System.out.println(SQL);
		try {
			Statement stmt = conn
					.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
							ResultSet.CONCUR_UPDATABLE);
			rs = stmt.executeQuery(SQL);

		} catch (Exception e) {
			System.out.println(e);
			Log.generateLog(ERROR, CLASS_NAME, METHOD_NAME,
					"Error while getting results from DB : " + e);
		}
		return rs;
	}

	public static void UpdateSQL(Connection conn, String UpdateSQL) {

		int rsd;
		try {
			Statement stmt = conn.createStatement();
			rsd = stmt.executeUpdate(UpdateSQL);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return;

	}

}
